package com.wgchao.identityrightsmanagement.query.vo;

import com.wgchao.identityrightsmanagement.infrastructure.jpa.entity.SysBaseAccount;
import com.wgchao.identityrightsmanagement.infrastructure.jpa.entity.SysBaseAgency;
import com.wgchao.identityrightsmanagement.infrastructure.jpa.entity.SysBaseDepartment;
import com.wgchao.identityrightsmanagement.infrastructure.jpa.repository.SysBaseAccountRepository;
import com.wgchao.identityrightsmanagement.infrastructure.jpa.repository.SysBaseAgencyRepository;
import com.wgchao.identityrightsmanagement.infrastructure.jpa.repository.SysBaseDepartmentRepository;
import com.wgchao.identityrightsmanagement.infrastructure.mapstruct.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @ClassName: AccountVoConvert
 * @author: wgchao
 * @createTime: 2020/6/16 9:22 AM
 * @Description: TODO
 */
@Component
public class AccountVoConvert {
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private SysBaseAccountRepository sysBaseAccountRepository;
    @Autowired
    private SysBaseDepartmentRepository sysBaseDepartmentRepository;
    @Autowired
    private SysBaseAgencyRepository sysBaseAgencyRepository;

    public AccountVo convert(SysBaseAccount sysBaseAccount) {

        AccountVo accountVo = accountMapper.toT(sysBaseAccount);

        if(!StringUtils.isEmpty(sysBaseAccount.getCreator())){
            SysBaseAccount creator = sysBaseAccountRepository.findFirstByUsername(sysBaseAccount.getCreator());
            accountVo.setCreatorName(creator == null ? null : creator.getName());
        }

        if(!StringUtils.isEmpty(sysBaseAccount.getLastUpdator())){
            SysBaseAccount updator = sysBaseAccountRepository.findFirstByUsername(sysBaseAccount.getLastUpdator());
            accountVo.setLastUpdatorName(updator == null ? null : updator.getName());
        }

        if(!StringUtils.isEmpty(sysBaseAccount.getDepartmentCode())){
            SysBaseDepartment sysBaseDepartment = sysBaseDepartmentRepository.findFirstByCode(sysBaseAccount.getDepartmentCode());
            accountVo.setDepartmentName(sysBaseDepartment == null ? null : sysBaseDepartment.getName());
        }

        SysBaseAgency sysBaseAgency = sysBaseAgencyRepository.findFirstByAgencyCode(sysBaseAccount.getAgencyCode());
        accountVo.setAgencyName(sysBaseAgency == null ? null : sysBaseAgency.getAgencyName());

        return accountVo;
    }
}
